package com.meicloud.license.appl.service.impl;

import com.meicloud.license.appl.service.LicenseService;
import com.meicloud.license.appl.vo.LicenseDto;
import com.meicloud.license.appl.vo.LicenseRegisterDto;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Map;

/**
 * license实现
 *
 * @author zhanghui145
 * @date 2022/1/10 14:55
 * @since 1.0.0
 */
@Service
public class LicenseServiceImpl implements LicenseService {

    @Resource
    private AesUtils aesUtils;

    @Resource
    private RsaUtils rsaUtils;

    // 这里应该放到缓存
    private static String RULE = null;
    // 这里应该放到缓存
    private static Map<String, String> rsaKey = null;

    @Override
    public String generateRegisterCode(LicenseRegisterDto register) {
        RULE = aesUtils.encryptRule();
        return aesUtils.encrypt(register, RULE);
    }

    @Override
    public String generateLicenseCode(String registerCode) {
        // 得到解密的注册码
        String registerInfo = aesUtils.decrypt(registerCode, RULE);
        Assert.notNull(registerInfo, "无效的注册码");
        rsaKey = rsaUtils.getKeyPairGenerator();
        return rsaUtils.encrypt("授权码code", rsaKey.get("privateKey"));
    }

    @Override
    public boolean register(String registerCode, String licenseCode) {
        String registerInfo = aesUtils.decrypt(registerCode, RULE);
        Assert.notNull(registerInfo, "无效的注册码");
        String licenseInfo = rsaUtils.decrypt(licenseCode, rsaKey.get("publicKey"));
        Assert.notNull(licenseInfo, "无效的授权码");
        return licenseInfo.contains("授权码code");
    }

    @Override
    public LicenseDto licenseStatus(String name, String sysIp, String sysName) {
        LicenseDto licenseDto = new LicenseDto();
        licenseDto.setName(name);
        licenseDto.setSysIp(sysIp);
        licenseDto.setSysName(sysName);
        licenseDto.setDuration(10);
        licenseDto.setEffective(true);
        return licenseDto;
    }
}
